<template>
  <div ref="wrapperRef" class="flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <ElCard class="sm:flex-1-hidden card-wrapper" body-class="ht50">
      <template #header>
        <div class="flex items-center justify-between">
          <p>分类管理</p>
          <ElButton type="primary" size="small" @click="InsertTJ()">添加</ElButton>
        </div>
      </template>
      <div class="mb-16px">
        <ElForm size="small">
          <ElRow>
            <ElFormItem label="状态">
              <ElSelect v-model="queryDto.status" placeholder="请选择">
                <ElOption label="全部" :value="-1"></ElOption>
                <ElOption label="正常" :value="1"></ElOption>
                <ElOption label="停用" :value="0"></ElOption>
              </ElSelect>
            </ElFormItem>
            <ElFormItem label="分类名称" style="margin-left: 20px;">
              <ElInput v-model="queryDto.roleName" placeholder="分类名称"></ElInput>
            </ElFormItem>
            <ElButton type="primary" size="small" @click="searchSysRole" style="margin-left: 20px;">搜索</ElButton>
            <ElButton size="small" @click="resetData">重置</ElButton>
          </ElRow>
        </ElForm>
      </div>

      <!-- 懒加载的树形表格 -->
      <div class="h-[calc(100%-50px)]">
        <ElTable
          :data="list"
          height="100%"
          border
          class="sm:h-full"
          row-key="id"
          lazy
          :load="fetchData"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        >
          <ElTableColumn prop="categoryName" label="分类名称" />
          <ElTableColumn prop="orderNum" label="排序" />
          <ElTableColumn prop="status" label="状态" #default="scope">
            {{ scope.row.status == 1 ? '正常' : '停用' }}
          </ElTableColumn>
          <ElTableColumn prop="createTime" label="创建时间" />
          <ElTableColumn label="操作" align="center" width="280" #default="scope">
            <div class="flex-center justify-end pr-10px">
              <ElButton type="primary" plain size="small" @click="Insert(scope.row)">添加子目录</ElButton>
              <ElButton type="warning" plain size="small" @click="Update(scope.row)">编辑</ElButton>
              <ElPopconfirm title="此操作将永久删除该记录, 是否继续?" @confirm="() => deleteById(scope.row)">
                {{
                  reference: () => (
                    <ElButton type="danger" plain size="small">删除</ElButton>
                  )
                }}
              </ElPopconfirm>
            </div>
          </ElTableColumn>
        </ElTable>
        <div class="mt-20px flex justify-end">
          <ElPagination
            v-if="list.length"
            layout="total,prev,pager,next,sizes"
            :total="list.length"
          />
        </div>
      </div>
    </ElCard>
  </div>

  <!-- 对话框 -->
  <ElDialog v-model="dialogVisible" :title="dialogTitle" width="30%">
    <ElForm label-width="120px">
      <ElFormItem label="分类名称">
        <ElInput v-model="sysMenu.categoryName"/>
      </ElFormItem>
      <ElFormItem v-if="!sysMenu.hasChildren" label="上级部门" prop="categoryId">
        <ElTreeSelect
          v-model="sysMenu.categoryId"
          :data="deptOptions"
          :props="{ value: 'id', label: 'name', isLeaf: 'leaf' }"
          :load="loadNode"
          lazy
          @visible-change="handleVisibleChange"
          value-key="id"
          placeholder="选择上级部门"
          check-strictly/>
      </ElFormItem>
      <ElFormItem label="排序">
        <ElInputNumber v-model="sysMenu.orderNum" :min="0" :max="100" />
      </ElFormItem>
      <ElFormItem label="状态">
        <ElRadioGroup v-model="sysMenu.status">
          <ElRadio :label="1">正常</ElRadio>
          <ElRadio :label="0">停用</ElRadio>
        </ElRadioGroup>
      </ElFormItem>
      <ElFormItem>
        <ElButton type="primary" @click="submit">提交</ElButton>
        <ElButton @click="dialogVisible = false">取消</ElButton>
      </ElFormItem>
    </ElForm>
  </ElDialog>
</template>

<script setup lang="tsx">
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox, ElButton, ElPopconfirm } from 'element-plus';
import { PictureById, findAll, SavePicture, UpdatePicture, RemovePicture } from '@/service/api/material/classify';


// 定义list属性模型
const list = ref([])

const queryDto = ref({
roleName: null,
status: -1
});

const searchSysRole = () => {
zy();
}

const resetData = () => {
queryDto.value = {}
}

const deptOptions = ref([]);

const dialogVisible = ref(false)
const dialogTitle = ref('')

const sysMenu = ref({
id: "",
categoryName: "",
status: 1,
orderNum: 1,
categoryId: "",
hasChildren:""
})

// 页面初始化完毕以后请求后端接口查询数据
onMounted(() => {
zy();
})

const zy = async () => {
  // const params = {
  //   status: queryDto.value.status,
  //   name: queryDto.value.roleName
  // };
  const { code, data, message } = await findAll();
  if (code === 200) {
    list.value = data; // 更新表格数据
  } else {
    ElMessage.error(message);
  }
};

const isLoaded = ref(false); // 标志位，确保数据只加载一次
// 当下拉框显示/隐藏时触发
const handleVisibleChange = async (visible) => {
if (visible && !isLoaded.value) {
    try {
      const res = await PictureById(0);
      deptOptions.value = res.data.map(item => ({
        id: item.id,
        name: item.categoryName,
        leaf: !item.hasChildren
      }));
      isLoaded.value = true; // 标记为已加载
    } catch (error) {
          console.error("加载数据失败:", error);
        }
      }
};

// 懒加载子节点
const loadNode = async (node, resolve) => {
  if (node.level === 0) {
    return resolve(deptOptions.value);
  }

  try {
    const parentId = node.data.id;
    const res = await PictureById(parentId);
    const nodes = res.data.map(item => ({
      id: item.id,
      name: item.categoryName,
      leaf: !item.hasChildren
    }));
    resolve(nodes);
  } catch (error) {
    console.error("加载子节点失败:", error);
    resolve([]); // 返回空数组，避免页面卡死
  }
};

// 加载数据的方法
const fetchData = async (row, treeNode, resolve) => {
const { code, data, message } = await PictureById(row.id)
resolve(data)
}

// 图像上传成功以后的事件处理函数
const handleAvatarSuccess = (response, uploadFile) => {
sysMenu.value.imageUrl = response.data
}

const submit = async () => {
if (!sysMenu.value.id) {
  const { code, message, data } = await SavePicture(sysMenu.value)
  if (code === 200) {
    dialogVisible.value = false
    ElMessage.success('操作成功')
  
  } else {
    ElMessage.error(message)
  }
} else {
  const { code, message, data } = await UpdatePicture(sysMenu.value)
  if (code === 200) {
    dialogVisible.value = false
    ElMessage.success('操作成功')
  } else {
    ElMessage.error(message)
  }
}
zy()
fetchData();
}

const deleteById = async (row) => {
  const { code, message } = await RemovePicture(row.id)
  if (code === 200) {
    ElMessage.success('删除成功')
    zy();
  } else {
    ElMessage.error(message)
  }
}
}

// 修改数据
const Update = async(row) => {

row.categoryId=row.categoryId===0?null:row.categoryId;
if(row.categoryId!=0){
  const res = await PictureById(0);
      deptOptions.value = res.data.map(item => ({
        id: item.id,
        name: item.categoryName,
        leaf: !item.hasChildren
      }));
      isLoaded.value = true; // 标记为已加载
}
sysMenu.value = row
dialogVisible.value = true;
dialogTitle.value = "修改"
}


const InsertTJ=()=>{
  sysMenu.value = {
  id: "-99",
  categoryName: "",
  categoryId: "",
  status: 1,
  orderNum: 1,
  hasChildren:true
}
dialogVisible.value = true;
dialogTitle.value = "添加"
}
// 添加数据
const Insert = async(row) => {
    const res = await PictureById(row.categoryId);
      deptOptions.value = res.data.map(item => ({
        id: item.id,
        name: item.categoryName,
        leaf: !item.hasChildren
      }));
      isLoaded.value = true; // 标记为已加载

sysMenu.value = {
  id: "",
  categoryName: "",
  categoryId: row.id,
  status: 1,
  orderNum: 1
}
dialogVisible.value = true;
dialogTitle.value = "添加"
}
</script>

<style lang="scss" scoped>
:deep(.el-card) {
  .ht50 {
    height: calc(100% - 50px);
  }
}

.flex-center {
  display: flex;
  align-items: center;
}

.justify-end {
  justify-content: flex-end;
}

.pr-10px {
  padding-right: 10px;
}

.mt-20px {
  margin-top: 20px;
}

.mb-16px {
  margin-bottom: 16px;
}
</style>